import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../common/SharedPreferencesHelper.dart';
import '../common/routes.dart';

class LoginController extends GetxController {
  var isLoading = false.obs;
  var username = 'admin'.obs;
  var password = '123456'.obs;

  late TextEditingController usernameController;
  late TextEditingController passwordController;

  @override
  void onInit() {
    super.onInit();

    usernameController = TextEditingController(text: username.value);
    passwordController = TextEditingController(text: password.value);
  }

  @override
  void onClose() {
    // 销毁控制器，防止内存泄漏
    usernameController.dispose();
    passwordController.dispose();
    super.onClose();
  }

  void login() async {
    isLoading.value = true;

    // 模拟网络请求延迟
    await Future.delayed(const Duration(seconds: 2));

    if (username.value == 'admin' && password.value == '123456') {
      // 登录成功
      await SharedPreferencesHelper.setString('token', 'e7b3a57d-cd74-4c6d-bf7e-d650c7a5cb1f');
      Get.offNamed(Routes.HOME);  // 跳转到首页
    } else {
      // 登录失败
      Get.snackbar('Login Failed', 'Invalid username or password');
    }

    isLoading.value = false;
  }
}
